import 'package:fig/spiders/general_spider.dart';
import 'package:fig/sqlite/sql_manager.dart';
import 'package:fig/utils/config.dart';
import 'package:flutter/material.dart';

import 'app.dart';
import 'events/spider_event.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SqlManager.init();
  loadData(); // 测试爬虫

  // 如果开启了爬虫则去执行爬取功能
  Config.eventBus.on<SpiderWorkingEvent>().listen((event) => event.start ? loadData() : null);

  runApp(MainApp());
}

class MainApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('开始初始化界面');
    // 设置主题样式
    Color _themeColor = Colors.green; //当前主题色
    final ThemeData _themeData = ThemeData(
      primarySwatch: _themeColor, // 主体颜色
      buttonTheme: ButtonThemeData(minWidth: 44.0),
      appBarTheme: AppBarTheme(elevation: 1),
      scaffoldBackgroundColor: Color(0xFFF5F5F5), // 脚手架背景色
    );

    return MaterialApp(
      debugShowCheckedModeBanner: false, // 去掉Debug
      theme: _themeData,
      title: '无花果电影',
      home: Scaffold(
        body: Center(
          child: BottomNavigationWidget(),
        ),
      ),
    );
  }
}

loadData() async {
  if (!await Config.autoSpider()) {
    print('未开启自动爬取，停止任务');
    return;
  }

  if (Config.spiderRunning) {
    print('爬虫已启动');
    return;
  }

  Config.spiderRunning = true;
  GeneralSpider.loadData(Config.spiderUrl());
}
